# -*- coding: utf-8 -*-

import libtcodpy as libtcod

import config
import sk_map, events, sk_input
import sys, time

from pprint import pprint
import inspect

#import pygame
#from pygame.locals import *

from time import gmtime, strftime


if config.__PYSKILLER_DEBUG:
	FOG_OF_WAR = False
	RIGHT_CLICK_DEBUG = True
else:
	FOG_OF_WAR = True	
	RIGHT_CLICK_DEBUG = False	

	
TYPE_FG = 1
TYPE_BG = 2	
	
#=======================================================================
#				Simple input event subsystem
#=======================================================================	

		
	

class GUI_element(object):
	def __init__(self, x, y, w, h, title=""):

		self.w = w
		self.h = h
		
		self.x = x
		self.y = y
		
		self.max_lines = self.h - 2
		
		self.title = title
		self.lines = []	
		
		self.owner = None

		self.back_color = libtcod.darker_gray
		self.front_color = libtcod.light_gray
		
		self.resizable = False
		
		self.visible = True
		
		
		#if em:
			#self.render = em.services["render"]
			
		self.border = True
		
	def set_border(self, border):
		self.border = border
		
		#if self.border:
		#	self.max_lines = self.h
		#	if self.max_lines <= 0:
		#		self.max_lines = 1
			
		#self.resize()
		
	def e_input_event(self, event):
		#this is entry point, lol
		#print self.title + ": - message recieved"
		
		if not self.visible:
			return
		
		if 	isinstance(event,sk_input.MouseInputEvent):
			i, j = event.x, event.y
			
			if i < self.x or i > self.x+self.w:
				return self.on_mouse_out(event)
			if j < self.y or j > self.y+self.h:
				return self.on_mouse_out(event)


			if event.dispatched:
				return
				
			self.on_mouse_event(event)
			event.dispatch()	#we cought event for teh great justice
			
			#self.render.message("");
			#print self.title + ": - message dispatched"
			
			
	#===================================================================
	def on_mouse_event(self,event):
		pass
	
	def on_mouse_out(self,event):
		pass	
	#===================================================================
		
	def add_line(self, msg, color = libtcod.light_gray):
		self.lines.append((msg, color))
		
		if self.resizable:
			self.max_lines += 1
			self.resize()

		if self.max_lines <= 0:
			print "GUI ERROR: max lines <= 0"
			return
		
		while len(self.lines) > self.max_lines:
			del self.lines[0]
			
	def clear(self):
		self.lines = []
		self.max_lines = 0		
		self.resize()
	
	def resize(self):
		border_h = 2
		if not self.border:
			border_h = 0
			
		self.h = border_h + len(self.lines)
		
		if self.h <= 0:
			self.h = 1
			
	def set_color(self,color = libtcod.light_gray):
		#self.front_color = color
		pass
		
	def set_owner(self,owner):
		self.owner = owner
		
	#this may be confusing
	#it is 'actual' init method
	
	#gui element should be bind to the event manager in order to take part in ENS	
		
	def bind(self,em):
		self.em = em
	

	def render(self):
		if self.owner and hasattr(self.owner,"visible") and not self.owner.visible:
			return
		
		if not self.visible:
			return
			
		self.panel = libtcod.console_new(self.w,self.h)

		libtcod.console_set_default_background(self.panel, self.back_color)
		libtcod.console_set_default_foreground(self.panel, self.front_color)
			
		libtcod.console_rect(self.panel, 0, 0, self.w, self.h, False)
			
		if self.border:	
			self.draw_border()
			
		if self.title:
			libtcod.console_print_ex(self.panel, 1, 0, libtcod.BKGND_NONE, libtcod.LEFT, "="+self.title+"=")
			
			#print "lines:"+str(self.max_lines)
			#print "rendering [%d,%d,%d,%d]" % (self.x, self.y, self.w, self.h)
			
		for i in range(len(self.lines)):
			if i <= self.max_lines and len(self.lines):
				#print self.lines
				#exit()
				
				libtcod.console_set_default_foreground(self.panel, self.lines[i][1])
				libtcod.console_print_ex(self.panel, 1, 1+i, libtcod.BKGND_NONE, libtcod.LEFT, self.lines[i][0])

		libtcod.console_set_default_background(self.panel, libtcod.black)	
		
		libtcod.console_blit(self.panel, 0, 0, self.w, self.h, 0, self.x, self.y)
		
	def draw_border(self):
		clr = self.front_color
		bg_clr = libtcod.darker_gray
		
		libtcod.console_put_char_ex(self.panel, 0, 0, libtcod.CHAR_NW, 					clr, bg_clr)
		libtcod.console_put_char_ex(self.panel, 0, self.h-1, libtcod.CHAR_SW, 			clr, bg_clr)
		libtcod.console_put_char_ex(self.panel, self.w-1, 0, libtcod.CHAR_NE, 			clr, bg_clr)
		libtcod.console_put_char_ex(self.panel, self.w-1, self.h-1, libtcod.CHAR_SE, 	clr, bg_clr)

		for i in range(self.h-2):
			libtcod.console_put_char_ex(self.panel, 0, i+1, libtcod.CHAR_VLINE, clr, bg_clr)
			libtcod.console_put_char_ex(self.panel, self.w-1, i+1, libtcod.CHAR_VLINE, clr, bg_clr)
			
		for j in range(self.w-2):
			libtcod.console_put_char_ex(self.panel, j+1, 0, libtcod.CHAR_HLINE, clr, bg_clr)
			libtcod.console_put_char_ex(self.panel, j+1, self.h-1, libtcod.CHAR_HLINE, clr, bg_clr)

	def hide(self):
		self.visible = False
		
	def show(self,x,y):
		
		self.x = x
		self.y = y
			
		if self.owner:
			if x + self.w > self.owner.w:
				self.x = self.owner.w-self.w
			if y + self.h > self.owner.h:
				self.y = self.owner.h-self.h
				
		print "showing menu @ %d, %d" % (self.x, self.y)
				
		self.visible = True

	def toggle(self):
		self.visible = not self.visible
		#print "visibility is set to " + str(self.visible)
#=======================================================================

class GUI_MessageBar(GUI_element):
	def __init__(self, x, y, w, h):
		super(GUI_MessageBar,self).__init__(x, y, w, h, None)
		#self.set_border(False)
		
		self.back_color = libtcod.dark_gray
	
	def set_message(self, message):
		#self.clear()

		self.add_line(message)
		

#=======================================================================

class GUI_TextList(GUI_element):
	def __init__(self, x, y, title):
		super(GUI_TextList,self).__init__( x, y, x+1, y+1, title)
		self.resizable = True	
			
	def add_line(self, msg, color = libtcod.light_gray):
		super(GUI_TextList,self).add_line(msg, color)
		
		max_len = len(self.title)+2
		for line in self.lines:
			if max_len < len(line[0]):
				max_len = len(line[0])
				
		self.w = 2 + max_len	#1 tile from left, 1 tile from right)
		
	def on_mouse_event(self,event):
		if event._type != "idle":
			menu_entry = event.y - self.y - 1
			if menu_entry >= 0 and  menu_entry < len(self.lines):
				self.on_line_click(menu_entry,event)
	
			
	def on_line_click(self, line_id, event):
		pass
	
#=======================================================================
class GUI_Menu(GUI_TextList):
	def __init__(self, title):
		super(GUI_Menu,self).__init__(0, 0, title)
		self.action_list = []

	def on_line_click(self,line_id, event):
		self.action_list[line_id].act(self.em.services["player"])
		self.hide()
		
	def on_mouse_out(self, event):
		if event._type != "idle":
			self.hide()
			
#=======================================================================
class GUI_Char_Stats(GUI_TextList):
	def update(self, em):
		self.clear()
		
		player = em.services["player"]
		
		self.add_line("HP: "+str(player.hp)+"/"+str(player.combat.get_max_hp()))
		self.add_line("Damage: "+str(player.combat.get_damage()))
		
		
		self.add_line("Stamina: "	+str( 
				int( (float(player.body.stamina) / player.combat.get_max_stamina()) * 100 ) 
			) + "%%" )
		self.add_line("Hunger: "	+str( 
				int(100 - player.body.hunger)) + "%%" )
		self.add_line("")
		
		self.add_line("Str:"+str(player.combat.stats.str))
		self.add_line("Per:"+str(player.combat.stats.per))
		self.add_line("End:"+str(player.combat.stats.end))
		self.add_line("Chr:"+str(player.combat.stats.chr))
		self.add_line("Int:"+str(player.combat.stats.int))
		self.add_line("Agi:"+str(player.combat.stats.agi))
		self.add_line("Luk:"+str(player.combat.stats.luk))
		
#-----------------------------------------------------------------------		
class GUI_Inventory(GUI_TextList):
	
	def update(self, em):
		self.clear()
		
		player = em.services["player"]
		
		for item in player.container.objects:
			if item in player.container.equipment:
				self.add_line(item.name, libtcod.white)
			else:
				self.add_line(item.name)
			
	def on_line_click(self,line_id, event):
		player = self.em.services["player"]
		
		#print "LINE CLICK"
		
		
		if event._type == "lmb":
			
			player.container.equip(player.container.objects[line_id])
			
		elif event._type == "rmb":

			obj = player.container.objects[line_id]
			a_list = obj.get_action_list()
			
			self.item_popup(line_id, a_list)
			
	def item_popup(self, line_id, a_list):
		render = self.em.services["render"]
		
		if a_list:
			menu = GUI_Menu("menu")
			menu.set_owner(self.owner)
				
				
			menu.add_line("foo")	#BUG BUG BUG
			
			for action in a_list:
				menu.add_line(action.name)
				menu.action_list.append(action)
					
			#WHAT
			
			
			render.context_popup(self.x + self.w/2, self.y+line_id, menu)
			#menu.show(self.x + self.w/2,self.y+line_id)
			#self.owner.elems.append(menu)
			
		else:
			print "failed to show popup, empty action list"	
		pass	
		
		
			
		
		
#-----------------------------------------------------------------------		
class GUI_Equip(GUI_TextList):
	
	def update(self, em):
		self.clear()
		
		player = em.services["player"]
		
		for item in player.container.equipment:
			self.add_line(item.name)
			
	def on_line_click(self,line_id, event):
		player = self.em.services["player"]
		
		print "unequiping item#"+str(line_id)
		player.container.unequip(player.container.equipment[line_id])
#=======================================================================
class GUI_WindowClose(GUI_element):
	
	def on_mouse_event(self,event):
		if event._type == "lmb":
			self.owner.toggle()
		
	def render(self):
		if self.owner and hasattr(self.owner,"visible") and not self.owner.visible:
			return
		
		if not self.visible:
			return
			
		#this shit is copepasted from gui element.
		#good refactoring is must there
		
		self.panel = libtcod.console_new(self.w,self.h)
		libtcod.console_set_default_foreground(self.panel, libtcod.light_gray)
		libtcod.console_set_default_background(self.panel, libtcod.dark_gray)
		
		libtcod.console_print_ex(self.panel, 1, 0, libtcod.BKGND_NONE, libtcod.LEFT, "X")
		libtcod.console_blit(self.panel, 0, 0, self.w, self.h, 0, self.x, self.y)
			
#-----------------------------------------------------------------------		

class GUI_Window(GUI_element):
	def __init__(self, x, y, w, h, title):
		super(GUI_Window,self).__init__(x, y, w, h, title)
		self.elems = []
		
		cross = GUI_WindowClose(self.x+self.w-3, self.y+1, 2 ,2)
		cross.visible = True
		cross.set_owner(self)
		
		self.elems.append(cross)
		
	def bind(self,em):
		super(GUI_Window,self).bind(em)

		for elem in self.elems:
			elem.bind(em)
			self.em.services["render"].add_gui(elem)
			
				
	def render(self):
		super(GUI_Window,self).render()
		
		for elem in self.elems:
			
			#-------this shit may be sloooow--------
			if hasattr(elem,"update"):
				elem.update(self.owner.em)
			#---------------------------------------
				
			elem.render()
			
#=======================================================================

class GUI_CharInfo(GUI_Window):
	def __init__(self, x, y, w, h):
		super(GUI_CharInfo,self).__init__(x, y, w, h, "Character info")
		self.visible = False
	
		
		
		#--------------character stats-------------------
		stats = GUI_Char_Stats(	self.x+2,self.y+2,"stats")
		stats.visible = True
		stats.set_owner(self)
		
		self.elems.append(stats)
		
		#--------------inventory-------------------------
		inv = GUI_Inventory(	self.x + 2, self.y+18,"inventory")
		inv.visible = True
		inv.set_owner(self)
		
		self.elems.append(inv)
		
		#--------------equiped-------------------------
		eq_inv = GUI_Equip(		self.x + 18, self.y+2,"equiped")
		eq_inv.visible = True
		eq_inv.set_owner(self)
		
		self.elems.append(eq_inv)
	
			
	
#=======================================================================
class GUI_ContPlayer(GUI_TextList):
	
	def update(self, em):
		self.clear()
		player = em.services["player"]
		
		for item in player.container.objects:
			self.add_line(item.name)
			
	def on_line_click(self,line_id, event):
		player = self.em.services["player"]
		
		item = player.container.objects[line_id]
		
		player.container.unequip(item)	#just to be sure
		player.container.objects.remove(item)
		self.owner.entity.container.append(item)
		
#-----------------------------------------------------------------------
class GUI_ContEnt(GUI_TextList):
	
	def update(self, em):
		self.clear()

		if self.owner.entity:
			for item in self.owner.entity.container.objects:
				self.add_line(item.name)
			
	def on_line_click(self,line_id, event):
		player = self.em.services["player"]
		
		entity = self.owner.entity
		
		item = entity.container.objects[line_id]
		player.container.objects.append(item)
		entity.container.remove(item)
#-----------------------------------------------------------------------
				
class GUI_ContainerContent(GUI_Window):
	def __init__(self, x, y, w, h):
		super(GUI_ContainerContent,self).__init__(x, y, w, h, "Container")
		self.visible = False
		#self.elems = []
		
		self.entity = None
		
		#--------------character inventory-------------------
		con_pl = GUI_ContPlayer(self.x+2, self.y+2, "player")
		con_pl.visible = True
		con_pl.set_owner(self)
		
		self.elems.append(con_pl)
		
		#--------------entity inventory-------------------------
		con_ent = GUI_ContEnt(self.x + 2+15, self.y+2, "container")
		con_ent.visible = True
		con_ent.set_owner(self)
		
		self.elems.append(con_ent)

			
#=======================================================================
#		PYSKILLER RENDERING ENGINE
#=======================================================================

class Render(events.EventListener):
	def __init__(self, w, h):
		super(Render,self).__init__()

		#self.em = em
		self.w = w
		self.h = h
		
		libtcod.console_set_custom_font('arial12x12.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)
		#libtcod.console_set_custom_font('lucida12x12_gs_tc.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)
		
		libtcod.console_init_root(w, h, 'Serial Killer Roguelike', False)
		self.con = libtcod.console_new(w, h)
		
		self.viewport = None
		self.gui_objects = []
		
		#---------------------------------------------------------------
		self.gui_console = GUI_element(0, 40, 80, 10, "console")
		#---------------------------------------------------------------
		ci_offset = 5
		self.gui_charinfo = GUI_CharInfo(ci_offset, ci_offset, self.w-ci_offset*2-2,self.h-ci_offset*2-2)
		self.add_gui(self.gui_charinfo)
		
		#---------------------------------------------------------------
		ci_offset = 8
		self.gui_container = GUI_ContainerContent(ci_offset, ci_offset, self.w-ci_offset*2-2,self.h-ci_offset*2-2)
		self.add_gui(self.gui_container)
		
		#---------------------------------------------------------------
		#self.gui_hintbar = GUI_MessageBar(self.w/2-8, 3, 16, 3)
		#self.gui_hintbar = GUI_MessageBar(self.w/2-8, 1, 16, 3)
		#self.add_gui(self.gui_hintbar)
		#self.gui_hintbar.visible = False
		
		#---------------------------------------------------------------
		self.viewport_map = None
		
	def synch_viewport(self):
		pass
		
	def render_map(self, map, fov_map):
		timer = self.em.services["sk_time"]
		if timer.is_night():
			sk_map.color_dark_ground = libtcod.gray
			sk_map.color_light_ground = libtcod.light_gray
			sk_map.color_dark_wall = libtcod.Color(0, 50, 100)
			sk_map.color_light_wall = libtcod.Color(50, 100, 100)
		
		else:
			sk_map.color_dark_wall = libtcod.Color(0, 0, 100)
			sk_map.color_light_wall = libtcod.Color(130, 110, 50)
			sk_map.color_dark_ground = libtcod.Color(50, 50, 150)
			sk_map.color_light_ground = libtcod.Color(200, 180, 50)
		'''	
		#experimental shit---------------------------
		self.BR = [0] * self.viewport.w * self.viewport.h
		self.BG = [0] * self.viewport.w * self.viewport.h
		self.BB = [0] * self.viewport.w * self.viewport.h
		#---------------------------------------------
		#experimental shit---------------------------
		self.FR = [255] * self.viewport.w * self.viewport.h
		self.FG = [255] * self.viewport.w * self.viewport.h
		self.FB = [255] * self.viewport.w * self.viewport.h
		#---------------------------------------------
		'''
		#===============================================================
		
		#print self.viewport.w
		#print self.viewport.h
		
		for i in range(self.viewport.w):
			for j in range(self.viewport.h):
				(x,y) = self.viewport.cord_world(i,j)
					
				#self.FB[self.viewport.w * j + i] = 100

				tile = map.get_tile(x,y)
				
				if tile:
					if FOG_OF_WAR:
						visible = self.em.services["fov"].tile_visible(x,y)	#0.14~0.16 ms
						if not visible:
							if tile.explored:
								self.RenderTile(tile,i,j,sk_map.color_dark_wall,sk_map.color_dark_ground)
								pass
						else:
							self.RenderTile(tile,i,j,sk_map.color_light_wall,sk_map.color_light_ground)
							tile.explored = True

					else:
						self.RenderTile(tile,i,j,sk_map.color_light_wall,sk_map.color_light_ground)
						
		#===============================================================					
		#libtcod.console_fill_background(self.con, self.BR, self.BG, self.BB)
		#libtcod.console_fill_foreground(self.con, self.FR, self.FG, self.FB)
		
						
	def RenderTile(self, tile, x, y, wall_color, ground_color):

		libtcod.console_set_default_foreground(self.con, libtcod.white)
		
		wall = tile.block_sight			
		if wall:
			self.set_tile_color(x,y,wall_color,TYPE_BG)
			libtcod.console_put_char(self.con, x, y, "#", libtcod.white)
	
		else:
			if tile.blood:
				self.set_tile_color(x,y,libtcod.red,TYPE_BG)
			else:
				self.set_tile_color(x,y,ground_color,TYPE_BG)
				
			if tile.is_owned():
				libtcod.console_put_char(self.con, x, y, ".", libtcod.red)
				
		#FOR SHIT LIKE GRASS OR TREES
		if tile.model and not tile.blood:
			if tile.color:
				mdl_color = tile.color
			else:
				mdl_color = libtcod.white	
				
			libtcod.console_put_char_ex(self.con, x, y, tile.model, mdl_color, ground_color)
								
		
		
	def add_gui(self, gui):
		self.gui_objects.append(gui)
		
		if not gui.owner:
			gui.set_owner(self)
			
	
	def set_em(self,em):
		super(Render,self).set_em(em)
			
		#self.gui_charinfo.set_em(self.em)
		#self.gui_container.set_em(self.em)
		for gui in self.gui_objects:
			gui.bind(self.em)
		
		
		
	def clear_all(self):
		for i in range(self.w):
			for j in range(self.h):
				libtcod.console_put_char(self.con, i, j, " ", libtcod.white)
				libtcod.console_set_char_background(self.con, i, j, libtcod.black, libtcod.BKGND_SET)
				
	def set_viewport(self, viewport):
		self.viewport = viewport
		
		self.synch_viewport()
				
	def render_objects(self):
		
		if self.viewport:
			for i in range(self.viewport.w):
				for j in range(self.viewport.h):
					tile = self.viewport.get_tile(self.em.services["map"],i,j)
					if tile:
						
						#FUCKING gazillion time faster
						for object in tile.objects:
							if object != self.em.services["player"] and (object not in self.em.services["sk_map_npc"]):
								self.draw_object(object)
								#pass
								
		for npc in self.em.services["sk_map_npc"]:
			self.draw_object(npc)			
			
	def set_tile_color(self, i, j, color, _type):
		if _type == TYPE_BG:
			'''self.BR[self.viewport.w * j + i] = color.r
			self.BG[self.viewport.w * j + i] = color.g
			self.BB[self.viewport.w * j + i] = color.b'''
			libtcod.console_set_char_background(self.con, i, j, color, libtcod.BKGND_SET)
		elif _type == TYPE_FG:
			'''self.FR[self.viewport.w * j + i] = color.r
			self.FG[self.viewport.w * j + i] = color.g
			self.FB[self.viewport.w * j + i] = color.b'''
			libtcod.console_set_char_foreground(self.con, i, j, color)
			
			
	
	def draw_object(self,object):
		if self.viewport:
			if FOG_OF_WAR:
				visible = self.em.services["fov"].tile_visible(object.x, object.y)
			else:
				visible = True
			#-----------------------------------------------------------
			
			if visible:
				(x,y) = self.viewport.cord_view(object.x, object.y)
				#print "viewport - ["+str(self.viewport.x)+","+str(self.viewport.y)+"]"
				if x < self.w and x > 0:
					if y < self.h and y > 0:
						#object.render(x,y,self.con)
						
						model = object.get_model()
						if not model:
							model = object.model
		
						libtcod.console_put_char(self.con, x, y, model, libtcod.BKGND_NONE)
						self.set_tile_color(x,y,	object.color,		TYPE_FG)
						
						if object.bg_color != libtcod.BKGND_NONE:
							self.set_tile_color(x,y,	object.bg_color,	TYPE_BG)
							
						
	#render every panel and component of gui					
	def render_GUI(self):

		self.gui_console.render()

		for gui in self.gui_objects:
			gui.render()	
		pass
		
	#Render various debug information, like travel pathes, etcetra	
	def render_debug(self):
		'''
		objects = self.em.services["objects"]
		for obj in objects:
			if hasattr(obj,"controller") and obj.controller:
				if obj.controller.path:
					for node in obj.controller.path:
						(i,j) = self.viewport.cord_view(node[0],node[1])
						if i > 0 and j > 0 and i < self.w-1 and j < self.h-1:
							libtcod.console_set_default_foreground(self.con, libtcod.red)
							libtcod.console_put_char(self.con, i, j, "*", libtcod.red)
							#libtcod.console_put_char_ex(self.con, i, j, libtcod.CHAR_BLOCK1, libtcod.red, libtcod.yellow)'''

	#remove me
	def message(self,msg, color = libtcod.light_gray):
		#self.gui_console.set_color(color)
		self.gui_console.add_line(strftime("[%H:%M:%S] ", gmtime()) + msg, color)
	
	def hint_tile(self, i , j):
		map = self.em.services["map"]
		tile = self.viewport.get_tile(map,i,j)
		
		if tile:
			(x,y) = self.viewport.cord_world(i,j)
			if len(tile.objects):
				for obj in tile.objects:
					self.gui_hintbar.set_message(obj.name)
					
					return
		
		self.gui_hintbar.set_message("")
		
	def describe_tile(self, map, i, j):
		tile = self.viewport.get_tile(map,i,j)
		if tile:
			(x,y) = self.viewport.cord_world(i,j)
			#for obj in map.get_objects(x,y):
			for obj in tile.objects:
				self.message("You see " + obj.name)
				obj.describe(self)

			if tile.obstacle:
				self.message("This tile is blocked with object")
				
	def e_input_event(self, event):
		
		for gui in reversed(self.gui_objects):
			gui.e_input_event(event)
			
			
		if event.dispatched:
			return
			
		if 	isinstance(event,sk_input.MouseInputEvent):
			if event._type == "lmb":
				self.e_mouse_lclick(event)
			if event._type == "rmb":
				self.e_mouse_rclick(event)
			#if event._type == "idle":
			#	self.e_mouse_idle(event)

	def e_mouse_idle(self,event):

		self.hint_tile(event.x, event.y)

	def e_mouse_lclick(self,event):
		self.describe_tile(self.em.services["map"], event.x, event.y)
		
	def e_mouse_rclick(self,event):
		i,j = event.x,event.y
		(x,y) = self.viewport.cord_world(i,j)

		if not event.dispatched:
			self.context_menu(i,j)
			
	def e_kb_tab(self):
		self.gui_charinfo.toggle()
					
	def context_menu(self,i, j):
		map = self.em.services["map"]
		#TODO: implement entity -> menu there
		
		for n in range(len(self.gui_objects)-1):
			if isinstance(self.gui_objects[n], GUI_Menu):
				del self.gui_objects[n]
			
			
		menu = GUI_Menu("menu")
		menu.set_owner(self)
			
		menu.add_line("foo")		#BUG!	This menu option is not adding to menu list	
			
		
		#obj = map.get_obstacle(x,y)
		
		#------------------------------------
		(x,y) = self.viewport.cord_world(i,j)
		tile = self.em.services["map"].get_tile(x,y)
		obj = None
		if len(tile.objects):
			obj = tile.objects[0]
		#------------------------------------
		
		player = self.em.services["player"]
		
		#TODO: auto-hide context menu on player movement!!!!11one
		
		
		if obj:
			#do not allow to call popup menu for distant objects
			if not RIGHT_CLICK_DEBUG:
				if ((player.x - x) ** 2 + (player.y - y) ** 2) > 1:
					return
			
			a_list = obj.get_action_list()
			
			if a_list:
				for action in a_list:
					menu.add_line(action.name)
					menu.action_list.append(action)
					
				#menu.show(i,j)
				#self.gui_objects.append(menu)
				self.context_popup(i,j,menu)
			else:
				print "no action list for obstacle '"+obj.name+"' @(%d, %d)" % (x,y)
		else:
			print "DEBUG: no obj @(%d, %d)" % (x,y)
			
	def context_popup(self, i, j, menu):
		menu.show(i,j)
		menu.bind(self.em)
		self.gui_objects.append(menu)
	
	
	def notify(self,event):
		if isinstance(event,events.PlayerOpenContainer):
			self.gui_container.toggle()
			self.gui_container.entity = event.entity
			
		if isinstance(event,events.ConsoleMsg):
			self.message(event.message)
